package com.example.demo.mp.controller;


import com.example.demo.mp.entity.ShortUrl;
import com.example.demo.mp.service.ShortUrlService;
import com.example.demo.tool.RedisTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;

/**
 * (Userinfo)表控制层
 *
 * @author makejava
 * @since 2024-12-14 16:02:11
 */
@RestController
@RequestMapping("s")
public class ShortController {
    /**
     * 服务对象
     */
    @Resource
    private ShortUrlService shortUrlService;

    @Value("${shortUrl.domain}")
    private String domain;

    @PostMapping("createShortUrl")
    public String createShortUrl(@RequestParam String url) {
        String shortUrl = domain + "/s/" + shortUrlService.createShortUrl(url).getShortName();
        return shortUrl;
    }

    @Resource
    RedisTool redisTool;

    @ResponseStatus(HttpStatus.MOVED_PERMANENTLY)
    @GetMapping("/{shortName}")
    public RedirectView redirectUrl(@PathVariable("shortName") String shortName) {
        redisTool.incrementCounter("clickCount:" + shortName, 1);

        ShortUrl shortUrl = shortUrlService.getShortUrl(shortName);
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl(shortUrl.getUrl());
        // 此种方案不需要前端做任何改变
        return redirectView;
    }

}

